package com.zzyl.serve.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.huaweicloud.sdk.core.auth.AbstractCredentials;
import com.huaweicloud.sdk.core.auth.ICredential;
import com.huaweicloud.sdk.core.exception.ConnectionException;
import com.huaweicloud.sdk.core.exception.RequestTimeoutException;
import com.huaweicloud.sdk.core.exception.ServiceResponseException;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.RedisKeyConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.serve.domain.Device;
import com.zzyl.serve.dto.DeviceDto;
import com.zzyl.serve.mapper.DeviceMapper;
import com.zzyl.serve.service.IDeviceService;
import com.zzyl.serve.vo.DeviceDetailVo;
import com.zzyl.serve.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Update;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 设备表Service业务层处理
 * 
 * @author yanbucai
 * @date 2025-05-07
 */
@Slf4j
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService
{
    @Autowired
    private DeviceMapper deviceMapper;

    /**
     * 查询设备表
     * 
     * @param id 设备表主键
     * @return 设备表
     */
    @Override
    public Device selectDeviceById(Long id)
    {
        return getById(id);
    }

    /**
     * 查询设备表列表
     * 
     * @param device 设备表
     * @return 设备表
     */
    @Override
    public List<Device> selectDeviceList(Device device)
    {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int insertDevice(Device device)
    {
        return save(device) ? 1 : 0;
    }

    /**
     * 修改设备表
     * 
     * @param device 设备表
     * @return 结果
     */
    @Override
    public int updateDevice(Device device)
    {
        return updateById(device) ? 1 : 0;
    }

    /**
     * 批量删除设备表
     * 
     * @param ids 需要删除的设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids)
    {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备表信息
     * 
     * @param id 设备表主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id)
    {
        return removeById(id) ? 1 : 0;
    }

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IoTDAClient client;

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest listProductsRequest = new ListProductsRequest();
        //设置条数
        listProductsRequest.setLimit(50);
        //发起请求
        ListProductsResponse response = client.listProducts(listProductsRequest);
        if(response.getHttpStatusCode() != 200){
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }
        //存储到redis
       List<ProductSummary>  productSummaries=response.getProducts();
        redisTemplate.opsForValue().set(RedisKeyConstants.IOT_ALL_PRODUCT_LIST, productSummaries);

    }
    /**
     * 从Redis查询产品列表:
     *
     */
//    @Override
//    public List<ProductVo> allProduct() {
//
//        // 1. 从Redis查询产品信息
////        List<ProductSummary> productList = (List<ProductSummary>) redisTemplate.opsForValue().get(RedisKeyConstant.IOT_ALL_PRODUCT_LIST);
//        List<ProductSummary> productList = Convert.toList(ProductSummary.class, redisTemplate.opsForValue().get(RedisKeyConstants.IOT_ALL_PRODUCT_LIST)) ;
//
//        // 2. 封装前端需要的vo
//        if (ObjectUtil.isEmpty(productList)){
//            return CollectionUtil.empty(List.class);
//        }
//
//        // 注意 list拷贝选择copyToList：
//        List<ProductVo> voList = BeanUtil.copyToList(productList, ProductVo.class);
//
//        return voList;
//    }


    /**
     * 查询所有产品列表
     *
     * @return 产品列表
     */
    @Override
    public List<ProductVo> allProduct() {
        // 1. 从Redis查询产品信息
        List<ProductVo> productList  = (List<ProductVo>) redisTemplate.opsForValue().get(RedisKeyConstants.IOT_ALL_PRODUCT_LIST);
        if (ObjectUtil.isEmpty(productList)){
            return List.of();
        }

        List<ProductVo>  voList= BeanUtil.copyToList(productList, ProductVo.class);
        return    voList;

    }

    /**
     * 注册设备
     * @param
     */
    @Override
    public void registerDevice(DeviceDto dto) {

        //1.判断设备名称name是否重复，（如果重复，抛出异常，终止运行）
        long countName = count(
                new LambdaQueryWrapper<Device>()
                        .eq(StrUtil.isNotBlank(dto.getDeviceName()), Device::getDeviceName, dto.getDeviceName())
        );
        if (countName > 0){
            //如果重复，抛出异常，终止运行
            throw new RuntimeException("设备名称重复");

        }

        //2.检验设备标识码nodeId是否重复
        long countNodeId = count(
                new LambdaQueryWrapper<Device>()
                        .eq(StrUtil.isNotBlank(dto.getNodeId()), Device::getNodeId, dto.getNodeId())
        );
        if (countNodeId > 0){
            throw new RuntimeException("设备标识码重复");
        }


        //3.校验同一位置（位置类型+绑定位置）是否绑定了同一类产品(产品唯一标识)
        long countProduct = count(
                new LambdaQueryWrapper<Device>()
                        .eq(Device::getLocationType, dto.getLocationType())
                        .eq(Device::getBindingLocation, dto.getBindingLocation())
                        .eq(Device::getPhysicalLocationType, dto.getPhysicalLocationType())
                        .eq(Device::getProductKey, dto.getProductKey())
        );
        if (countProduct > 0){
            throw new RuntimeException("同一位置绑定了同一类产品");
        }


        //4.在iot平台中新增设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.setProductId(dto.getProductKey());
        body.setDeviceName(dto.getDeviceName());
        body.setNodeId(dto.getNodeId());

        // 设置设备的秘钥
        String scret = UUID.randomUUID().toString().replaceAll("-", "");
        AuthInfo authInfo = new AuthInfo();
        authInfo.setSecret(scret);
        body.withAuthInfo(authInfo);

        request.withBody(body);

        // 发送请求
        String iotId = "";
        try {
            AddDeviceResponse response = client.addDevice(request);
            iotId = response.getDeviceId();
        }catch (Exception e){
            // 抛出异常 终止运行‘
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }


        //5.设备数据保存到数据库
        // 对象属性拷贝
        Device device = BeanUtil.toBean(dto, Device.class);
        device.setSecret(scret);
        device.setIotId(iotId);

        // 保存
        save(device);

    }


    /**
     * 查询设备详情
     *
     * @return
     */
    @Override
    public DeviceDetailVo queryDeviceDetail(String iotId) {
        //查询数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            return null;
        }

        //调用华为云物联网接口
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            log.info("物联网接口 - 查询设备详情，调用失败:{}", e.getMessage());
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }

        //属性拷贝
        DeviceDetailVo deviceVo = BeanUtil.toBean(device, DeviceDetailVo.class);

        deviceVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if(ObjectUtil.isNotEmpty(activeTimeStr)){
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceVo.setActiveTime(activeTime);
        }

        return deviceVo;
    }

    /**
     * 查看设备上报的数据
     * @param iotId
     * @return
     */
    @Override
    public  List<Map>  queryServiceProperti(String iotId) {

        // 1. 先查询IOT平台，得到设备最新上报的数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);

        try {
            ShowDeviceShadowResponse response = client.showDeviceShadow(request);

            // 2. 解析响应数据
            Object properties = response.getShadow()
                    .get(0)
                    .getReported()
                    .getProperties();

            // json对象
            JSONObject jsonObject = JSONUtil.parseObj(properties);

            // 上报时间
            String eventTimeStr = response.getShadow().get(0).getReported().getEventTime();


            // 3. 封装数据：
            List list = new ArrayList<>();

            // 需要对日期格式进行单独处理
            //处理上报时间日期
            LocalDateTime activeTime = LocalDateTimeUtil.parse(eventTimeStr, "yyyyMMdd'T'HHmmss'Z'");
            //日期时区转换
            LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            jsonObject.forEach((key, value) -> {
                Map<String, Object> map = new HashMap<>();
                map.put("functionId", key);
                map.put("value", value);
                map.put("eventTime", eventTime);

                list.add(map);
            });

            return list;


        } catch (Exception e) {
            // 如果有异常，终止运行
            e.printStackTrace();
            throw new BaseException("物联网接口 - 查看设备上报的数据，调用失败");
        }
    }

    /**
     * 修改设备
     * @param
     */
    @Override
    public void editDevice(DeviceDto device) {


        // 判断设备名称是否重复
        LambdaQueryWrapper<Device> deviceNameWrapper = new LambdaQueryWrapper<Device>().eq(Device::getDeviceName, device.getDeviceName());
        if (this.count(deviceNameWrapper) > 0) {
            throw new RuntimeException("设备名称重复");
        }
        // 判断同一位置是否绑定了相同产品
        LambdaQueryWrapper<Device> productWrapper = new LambdaQueryWrapper<Device>()
                .eq(Device::getLocationType,device.getLocationType()) // 位置类型 0：随身设备 1：固定设备
                .eq(Device::getPhysicalLocationType,device.getPhysicalLocationType()) // 物理位置类型 0楼层 1房间 2床位  如果是随身设备，传-1
                .eq(Device::getBindingLocation,device.getBindingLocation()) // 老人id or 房间id or 床位id
                .eq(Device::getDeviceDescription,device.getDeviceDescription()); // 楼层id、房间id、床位id or 楼层id和房间id or 老人id
        if (this.count(productWrapper) > 0) {
            throw new RuntimeException("同一位置只能绑定一个产品");
        }
        // 修改IOT平台设备数据
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        UpdateDevice body = new UpdateDevice();
        body.withDeviceName(device.getDeviceName());  // 设备名称

        request.withBody(body);
        request.withDeviceId(device.getIotId());

        try {
            UpdateDeviceResponse response = client.updateDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("IOT平台修改设备失败");
        }
        // 修改数据库设备信息
        Device device1 = BeanUtil.toBean(device, Device.class);
        this.updateById(device1);
    }

    /**
     * 删除设备
     * @param iotId
     */
    @Override
    public void deleteDevice(String iotId) {

//查询数据库
        Device device = getOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, iotId));
        if (ObjectUtil.isEmpty(device)) {
            return ;
        }

        //调用华为云物联网接口
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.setDeviceId(iotId);

        DeleteDeviceResponse   response;
        try {
            response = client.deleteDevice(request);
        } catch (Exception e) {
            log.info("物联网接口 - 查询设备详情，调用失败:{}", e.getMessage());
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }
        deviceMapper.delete(new LambdaQueryWrapper<Device>().eq(Device::getIotId, iotId));
    }
}

